#!/usr/bin/python
#-*-coding=UTF-8-*- 

from UpCode import file_code
from UpCode import get_file_type
from UpCode import FileDataBase
from UpCode import color
import re
import os 
import sqlite3
import time 


Die = {'picture' :"Pictures",'music' : "Music",'document' : "Documents" ,'movie' : "Movies" }

class NewData(FileDataBase):
    def __init__(self):
        self.cx = sqlite3.connect("/Users/darkh/.programer_type_DB")
        self.cu = self.cx.cursor()
        try:
            self.cu.execute("""create table file_type (id integer primary key ,classification text, type_language text UNIQUE ) """)
            print "hello qingluan"
        except sqlite3.OperationalError :
            pass
    def insert_type(self,pro_type):
        count = self.size()
        number = count+1
        count_list = self.get_all_id()

        for i2 in range(count):
            if i2 not in  count_list:
                number =   i2

        self.cu.execute('insert into file_type values(%d,"%s","%s") '%(number,pro_type[0],pro_type[1]))
        self.cx.commit()  
    def size(self):
        self.cu.execute("select * from file_type")
        type_all = self.cu.fetchall()
        return len(type_all)     
    def get_type(self,type_cla):
        self.cu.execute("select * from file_type   where classification='%s'"%type_cla)
        res = self.cu.fetchall()
        return map((lambda x: x[2]),res)
    def get_all_in_DB(self):
        self.cu.execute("select * from file_type")
        res = self.cu.fetchall()
        return map((lambda x: x[2]),res)
    def get_all_id(self):
        self.cu.execute("select * from file_type")
        res = self.cu.fetchall()
        return map((lambda x:  x[0]),res)
    def close(self):
        if (self.cu ):
            self.cu.close()
            self.cx.close()

class Classification(file_code):
    def __init__(self):
        print "initializing ..."
        time.sleep(0.3)
        self.Path = os.getcwd() + "/Downloads/"
        self.Judege = os.popen("ls ~/Downloads").readlines()
        self.List_all_in_downloads =[]
        print "... ok"
        print "load..."
        time.sleep(0.3)
        self.DataBase = NewData()
        self.color_blue = color("blue")
        self.color_green = color("green")
        self.all_in_Downloads()
        print "color ..load -----ok"
        time.sleep(0.3)
        print "Database ..load --ok"
        #os.system("clear")
    def copy_code(self,item):
        if self.List_all_in_downloads:
            item = item[0:-1]
        else:
            print "~/Downlaods/ No File you need to classify! Qingluan\n"
            time.sleep(0.3)
            exit(0)
        directory = self.classification(item)
        if directory :
            pass
        else:
            print "No such file!\n"+"bug: " +direction
        if " " in item:
            item = self.string_do(item)
         #   item = string_do(item)
          
        some_code = os.system("cp -v  " + self.Path + item + " /Users/darkh/" + directory + "/")
        if some_code== 512:
            print "can't cp because '\( \)'" +item
        
            # print  ("cp -v  " + self.Desk_path + item + "  /Users/darkh/Dropbox/seed/"+ directory  + "/")
        #print("rm   " + self.Path + item )
    def string_do(self,item):
        if " " in item: 
            first = item.split(" ")
            second = map((lambda x: x+"\ "),first)
            third = ""
            for i in second:
                third += i
            forth = third[:-2]
        return forth
    def rm_code(self,item):
        if self.List_all_in_downloads:
            item = item[:-1]
        else:
            exit(0)
        if " " in item:
            item = self.string_do(item)
        directory = self.classification(item)
        os.system("rm " + self.Path+item)
    def classification(self,item):
        type_item =get_file_type_without_point(item)
        type_item = type_item[1:]
        #print type_item ##for test
        temp_type = [Die[key] for key in Die.keys() ] 
        for ty in temp_type:
            all_type = self.DataBase.get_type(ty)
            for item_type in all_type:
                if type_item in item_type:
                    return ty+"/"+type_item
    def all_in_Downloads(self):
        tem =  os.popen("ls /Users/darkh/Downloads/").readlines()
        type_list = self.DataBase.get_all_in_DB()
        for item in type_list:
            for item2 in tem:
                try:
                    if item in str(item2) :
                        print "%s" %self.color_blue.get_color(str(item2))
                        self.List_all_in_downloads.append(str(item2))
                except UnicodeDecodeError:
#############follow is very import !!!!! to get some chinese thing
                    spe_item = str(item)
                    spe_item2 = str(item2)
                    if spe_item in spe_item2:
                        self.List_all_in_downloads.append(spe_item2)
                        print "%s" %self.color_green.get_color(spe_item2)
                    else :
                        pass
        #print self.List_all_in_downloads   #for test 
    def update(self):
        if self.Judege:
            pass
        else:
            exit(0)
        if (raw_input("sure to trans ? (%s) >"% self.color_green.get_color("y/n")) =='y'):
            map(self.copy_code,self.List_all_in_downloads)
            map(self.rm_code,self.List_all_in_downloads)
            print "%s" %self.color_blue.get_color("\t\t Good bye ! \n\t\t\t Qing Luan")
            print "%s" %self.color_blue.get_color(time.ctime())
        time.sleep(1.5)
        #os.system("clear")
            

def get_file_type_without_point(string):
    compiler = re.compile('(\.[a-zA-Z]{1,7}[34]{0,1})')
    tem = re.findall(compiler,string)
    return tem[-1]



def run():
    cla = Classification()
    cla.update()
if __name__=="__main__":
    run()
